using System;
using System.Collections.Generic;
using System.Text;

using System.Data;
using System.Data.SqlClient;

namespace DataAccessLayer
{
    public class GenreGateway
    {
        private SqlConnection connection;
        private SqlDataAdapter adapter;
        private SqlCommand command;
        private SqlCommandBuilder builder;

        public GenreGateway(SqlConnection connection)
        {
            this.connection = connection;
            command = new SqlCommand("SELECT * FROM Genre WHERE id=@id", connection);
            command.Parameters.Add("@id", SqlDbType.BigInt);
            adapter = new SqlDataAdapter(command);
            builder = new SqlCommandBuilder(adapter);
        }

        public long Insert(string genreName, RecordingDataSet recordingDataSet) {
            RecordingDataSet.GenreRow newGenre = recordingDataSet.Genre.NewGenreRow();
            newGenre.id = IdGenerator.GetNextId(recordingDataSet.Genre.TableName, connection);
            newGenre.name = genreName;
            recordingDataSet.Genre.AddGenreRow(newGenre);
            Update(recordingDataSet);
            return newGenre.id;
        }

        public RecordingDataSet.GenreRow FindById(long searchedId, RecordingDataSet recordingDataSet) {
            command.Parameters["@id"].Value = searchedId;
            adapter.Fill(recordingDataSet, recordingDataSet.Genre.TableName);
            DataRow[] rows = recordingDataSet.Genre.Select(String.Format("id={0}", searchedId));

            if (rows.Length < 1) return null;

            return (RecordingDataSet.GenreRow)rows[0];
        
        }

        public void Delete(long deletedId, RecordingDataSet recordingDataSet)
        {
            RecordingDataSet.GenreRow foundRow = FindById(deletedId, recordingDataSet);
            foundRow.Delete();
            Update(recordingDataSet);
        }

        public void Update(RecordingDataSet recordingDataSet)
        {
            adapter.Update(recordingDataSet, recordingDataSet.Genre.TableName);
        }
    }
}
